﻿#include "XQFileSelectionWidget.h"
#include"XQGraphicsViewWidget.h"
#include<QEvent>
#include<QMenu>
#include<QCloseEvent>
#include<QFileDialog>
XQFileSelectionWidget::XQFileSelectionWidget(QWidget* parent)
	:XQFileTableWidget(parent)
{
	init();
}

XQFileSelectionWidget::~XQFileSelectionWidget()
{
}

bool XQFileSelectionWidget::activityAutoClose() const
{
	return m_AutoClose;
}

void XQFileSelectionWidget::changeEvent(QEvent* event)
{
	//窗口不是激活状态将关闭
	if (m_AutoClose&&event->type() == QEvent::ActivationChange)
	{
		if (!isActiveWindow()) 
		{
			deleteLater();
		}
	}
	QWidget::changeEvent(event);
}

void XQFileSelectionWidget::closeEvent(QCloseEvent* event)
{
	if (m_GraphicsViewWidget != nullptr)
	{
		event->ignore();//不要关闭窗口
		return;
	}
}

void XQFileSelectionWidget::setActivityAutoClose(bool flag)
{
	m_AutoClose = flag;
}

void XQFileSelectionWidget::init()
{
	setWindowFlags(Qt::FramelessWindowHint);  // 将窗口去除边框
	activateWindow();//激活窗口
	setSelectionMode(QAbstractItemView::SingleSelection);//一次选择一个
	//setChangeNameFlag(false);
	//断开父的双击打开文件
	disconnect(this, &QTableWidget::cellDoubleClicked, nullptr, nullptr);
	//链接双击信号为选择
	connect(this, &QTableWidget::cellDoubleClicked, [this] {
		auto it=item(currentRow(), Type::name);
		if(it!=nullptr)
		emit selectFile(it->data(Qt::UserRole).toString());
		close();});

	QMenu* menu = new QMenu(this);
	setMenu(menu);
	menu->setFont(QFont("黑体", 15));
	menu->addAction("选择文件", [=] {emit selectFile(item(currentRow(), Type::name)->data(Qt::UserRole).toString());close(); });
	menu->addAction("预览文件", [=] {
		m_GraphicsViewWidget = new XQGraphicsViewWidget();
		connect(m_GraphicsViewWidget, &XQGraphicsViewWidget::destroyed, [this] {m_GraphicsViewWidget = nullptr; });
		m_GraphicsViewWidget->setAttribute(Qt::WA_DeleteOnClose);
		//m_GraphicsViewWidget->setAutoDelete(true);
		m_GraphicsViewWidget->setPixmap(item(currentRow(), Type::name)->data(Qt::UserRole).toString());
		m_GraphicsViewWidget->show(); });
	menu->addSeparator();
	QString options = QString("Image Files(%1)").arg(QStringList(IMAGENAMEFILTERS).join(" "));//图片文件过滤器
	menu->addAction("上传文件", [=] { auto file=QFileDialog::getOpenFileName(this,"选择图片",QString(), options); addFile({file}); });
	menu->addAction("删除文件", [this] {removeFile({ item(currentRow(), Type::name)->data(Qt::UserRole).toString() }); });
	
	menu->addAction("重命名文件", [this] {editItem(item(currentRow(), Type::name));  });
}
